package com.stone.stone_mall.nosql.elasticsearch.service.impl;

import com.stone.stone_mall.nosql.elasticsearch.dao.EsProductDao;
import com.stone.stone_mall.nosql.elasticsearch.docment.EsProduct;
import com.stone.stone_mall.nosql.elasticsearch.repository.EsproductRepository;
import com.stone.stone_mall.nosql.elasticsearch.service.EsProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class EsProductServiceImpl implements EsProductService {
    private static final Logger LOGGER = LoggerFactory.getLogger(EsProductServiceImpl.class);
    @Autowired
    private EsProductDao productDao;
    @Autowired
    private EsproductRepository productRepository;

    @Override
    public int importAll() {
        List<EsProduct> esProList = productDao.getAllEsProductList(null);
        LOGGER.info(esProList.toString());
        Iterable<EsProduct> iterable = productRepository.saveAll(esProList);
        Iterator<EsProduct> iterator = iterable.iterator();
        int result=0;
        while (iterator.hasNext()){
            result ++;
            iterator.next();
        }

        return result;
    }

    @Override
    public void delete(Long id) {
        productRepository.deleteById(id);
    }

    @Override
    public EsProduct create(Long id) {

       EsProduct result=null;
        List<EsProduct> productList = productDao.getAllEsProductList(id);
        if(productList.size()>0){
            LOGGER.info(id.toString());
            EsProduct esProduct = productList.get(0);
            result=productRepository.save(esProduct);
        }

        return result;
    }

    @Override
    public void delete(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)){
            List<EsProduct>esProductList=new ArrayList<>();
            for (Long id:ids){
                EsProduct esProduct=new EsProduct();
                esProduct.setId(id);
                esProductList.add(esProduct);
            }
            productRepository.deleteAll(esProductList);
        }
    }

    @Override
    public Page<EsProduct> search(String keyword, Integer pageNum, Integer pageSize) {
//        Pageable pageable =  PageRequest.of(pageNum, pageSize);
        PageRequest pageable;
        pageable=PageRequest.of(pageNum,pageSize);
        Page<EsProduct> result = productRepository.findByNameOrSubTitleOrKeywords(keyword, keyword, keyword, pageable);
        return result;
    }
}
